package com.hwpt.chesedemo.data.remote.llm

import android.util.Log
import com.alibaba.dashscope.aigc.generation.Generation
import com.alibaba.dashscope.aigc.generation.GenerationParam
import com.alibaba.dashscope.common.Message
import com.alibaba.dashscope.exception.ApiException
import com.alibaba.dashscope.exception.NoApiKeyException
import com.alibaba.dashscope.utils.Constants
import com.hwpt.chesedemo.presentation.theme.LanguageManager
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject

class AiService @Inject constructor() {
    private val TAG = "AiService"
    private val API_KEY = "sk-c0f76c2c02104d8e8590bbcdc1764db5"

    // 获取当前语言代码
    private val currentLanguageCode: String
        get() = LanguageManager.currentLanguageCode

    init {
        Constants.apiKey = API_KEY
    }

    // 流式输出版本 - 使用 RxJava 2 Flowable
    fun aiTeachingStream(question: String): Flowable<String> {
        return Flowable.create({ emitter ->
            try {
                // 构建系统提示词和用户消息
                val systemMessage = Message.builder()
                    .role("system")
                    // 使用函数获取系统提示词，传入语言代码
                    .content(PromptTemplates.getChessTeachingSystemPrompt(currentLanguageCode))
                    .build()

                val userMessage = Message.builder()
                    .role("user")
                    .content(question)
                    .build()

                val messages = listOf(systemMessage, userMessage)

                val param = GenerationParam.builder()
                    .model("qwen-turbo")
                    .messages(messages)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .incrementalOutput(true)
                    .build()

                Log.d(TAG, "开始调用千问API流式输出，问题: $question")
                Log.d(TAG, "当前语言环境: $currentLanguageCode")

                val generation = Generation()

                // 直接调用 streamCall 返回 Flowable
                val streamResponse = generation.streamCall(param)


                // 订阅流响应
                streamResponse
                    .subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.computation())
                    .subscribe(
                        { result ->
                            try {
                                val content = result.output?.choices?.firstOrNull()?.message?.content
                                if (!content.isNullOrBlank()) {
                                    Log.d(TAG, "收到流式响应片段: $content")
                                    emitter.onNext(content)
                                }

                                // 检查是否结束
                                val finishReason = result.output?.choices?.firstOrNull()?.finishReason
                                if (finishReason != null && finishReason != "null") {
                                    Log.d(TAG, "流式输出完成，用量信息: ${result.usage}")
                                    emitter.onComplete()
                                }
                            } catch (e: Exception) {
                                Log.e(TAG, "处理流式响应错误", e)
                                if (!emitter.isCancelled) {
                                    emitter.onError(e)
                                }
                            }
                        },
                        { error ->
                            Log.e(TAG, "流式调用错误", error)
                            if (!emitter.isCancelled) {
                                emitter.onError(error)
                            }
                        },
                        {
                            Log.d(TAG, "流式输出正常完成")
                            if (!emitter.isCancelled) {
                                emitter.onComplete()
                            }
                        }
                    )

            } catch (e: Exception) {
                Log.e(TAG, "初始化流式调用错误", e)
                if (!emitter.isCancelled) {
                    emitter.onError(e)
                }
            }
        }, BackpressureStrategy.BUFFER)
            .subscribeOn(Schedulers.io())
            .onBackpressureBuffer()
    }

    suspend fun aiReview(question: String): String {
        return withContext(Dispatchers.IO) {
            try {
                // 构建系统提示词
                val systemMessage = Message.builder()
                    .role("system")
                    // 使用函数获取系统提示词，传入语言代码
                    .content(PromptTemplates.getChessAnalysisSystemPrompt(currentLanguageCode))
                    .build()

                val userMessage = Message.builder()
                    .role("user")
                    .content(question)
                    .build()

                val messages = listOf(systemMessage, userMessage)

                val param = GenerationParam.builder()
                    .model("qwen3-max")
                    .messages(messages)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build()

                Log.d(TAG, "开始调用千问API，问题: $question")
                Log.d(TAG, "当前语言环境: $currentLanguageCode")

                val generation = Generation()
                val result = generation.call(param)

                Log.d(TAG, "API返回结果: $result")

                if (result == null) {
                    Log.e(TAG, "API返回结果完全为空")
                    return@withContext "API返回结果完全为空"
                }

                // 尝试不同的响应格式
                if (result.output?.text != null) {
                    Log.d(TAG, "找到output.text: ${result.output.text}")
                    return@withContext result.output.text
                }

                if (result.output?.choices != null && result.output.choices.isNotEmpty()) {
                    val choice = result.output.choices[0]
                    val response = choice.message?.content ?: "消息内容为空"
                    Log.d(TAG, "通过choices获取响应: $response")
                    return@withContext response
                }

                if (result.output != null) {
                    Log.d(TAG, "直接使用output: ${result.output}")
                    return@withContext result.output.toString()
                }

                Log.e(TAG, "无法解析API响应")
                "无法解析API响应"

            } catch (e: NoApiKeyException) {
                Log.e(TAG, "API密钥错误", e)
                "API密钥错误: ${e.message}"
            } catch (e: ApiException) {
                Log.e(TAG, "API调用异常", e)
                "API调用异常: ${e.message}"
            } catch (e: Exception) {
                Log.e(TAG, "其他错误", e)
                "其他错误: ${e.message}"
            }
        }
    }

    /**
     * 水平评估 - 专门用于评估棋手水平
     */
    suspend fun aiEvaluation(question: String): String {
        return withContext(Dispatchers.IO) {
            try {
                // 构建系统提示词
                val systemMessage = Message.builder()
                    .role("system")
                    // 使用函数获取系统提示词，传入语言代码
                    .content(PromptTemplates.getChessEvaluationSystemPrompt(currentLanguageCode))
                    .build()

                val userMessage = Message.builder()
                    .role("user")
                    .content(question)
                    .build()

                val messages = listOf(systemMessage, userMessage)

                val param = GenerationParam.builder()
                    .model("qwen3-max") // 可以根据需要改为 qwen3-max
                    .messages(messages)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build()

                Log.d(TAG, "开始调用水平评估API，问题长度: ${question.length}")
                Log.d(TAG, "当前语言环境: $currentLanguageCode")

                val generation = Generation()
                val result = generation.call(param)

                Log.d(TAG, "水平评估API返回结果: ${result?.output?.choices?.firstOrNull()?.message?.content}")

                if (result == null) {
                    Log.e(TAG, "水平评估API返回结果完全为空")
                    return@withContext "{}"
                }

                // 解析响应
                val response = when {
                    result.output?.choices != null && result.output.choices.isNotEmpty() -> {
                        result.output.choices[0].message?.content ?: "{}"
                    }
                    result.output?.text != null -> result.output.text
                    else -> "{}"
                }

                Log.d(TAG, "水平评估响应: $response")
                return@withContext response

            } catch (e: NoApiKeyException) {
                Log.e(TAG, "API密钥错误", e)
                "{}"
            } catch (e: ApiException) {
                Log.e(TAG, "API调用异常", e)
                "{}"
            } catch (e: Exception) {
                Log.e(TAG, "水平评估其他错误", e)
                "{}"
            }
        }
    }
}